package com.example.final_project.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import com.example.final_project.service.UserService;
import com.example.final_project.service.PublisherService;
import com.example.final_project.service.BookService;
import com.example.final_project.service.OrderService;
import org.springframework.ui.Model;
import com.example.final_project.entity.User;

@Tag(name = "首页", description = "首页相关的API接口")
@Controller
public class HomeController {
    @Autowired
    private UserService userService;
    @Autowired
    private PublisherService publisherService;
    @Autowired
    private BookService bookService;
    @Autowired
    private OrderService orderService;

    @Operation(summary = "首页", description = "返回系统首页")
    @GetMapping({"/", "/main"})
    public String main(HttpSession session) {
        if (session.getAttribute("user") == null) {
            return "redirect:/user/login";
        }
        return "main";
    }

    @GetMapping("/home")
    public String home(HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        model.addAttribute("user", user);
        model.addAttribute("userCount", userService.countAllUsers());
        model.addAttribute("publisherCount", publisherService.countAllPublishers());
        model.addAttribute("bookCount", bookService.countAllBooks());
        model.addAttribute("orderCount", orderService.countAllOrders());
        model.addAttribute("userTypeStats", userService.getUserTypeStats() != null ? userService.getUserTypeStats() : new java.util.HashMap<>());
        model.addAttribute("orderStatusStats", orderService.getOrderStatusStats() != null ? orderService.getOrderStatusStats() : new java.util.HashMap<>());
        model.addAttribute("latestUsers", userService.getLatestUsers(5) != null ? userService.getLatestUsers(5) : new java.util.ArrayList<>());
        model.addAttribute("latestBooks", bookService.getLatestBooks(5) != null ? bookService.getLatestBooks(5) : new java.util.ArrayList<>());
        model.addAttribute("latestPublishers", publisherService.getLatestPublishers(5) != null ? publisherService.getLatestPublishers(5) : new java.util.ArrayList<>());
        model.addAttribute("latestOrders", orderService.getLatestOrders(5) != null ? orderService.getLatestOrders(5) : new java.util.ArrayList<>());
        model.addAttribute("orderTrend7Days", orderService.getOrderTrend7Days() != null ? orderService.getOrderTrend7Days() : new java.util.ArrayList<>());
        model.addAttribute("announcement", "欢迎使用教材管理系统！如有问题请联系管理员。");
        return "home";
    }
} 